﻿using NLog;
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace GBT.Tool.Core
{
    public class HttpRequest
    {
        private Logger logger = LogManager.GetCurrentClassLogger();

        #region 信任https请求证书
        private static bool RemoteCertificateValidate(
            object sender, X509Certificate cert,
             X509Chain chain, SslPolicyErrors error)
        {
            return true;
        }
        #endregion

        /// <summary>
        /// 该方法主要是处理POST请求,返回处理返回的结果字符串
        /// </summary>
        /// <param name="posturl">请求的接口链接</param>
        /// <param name="postdata">请求的数据</param>
        /// <returns>返回的结果</returns>
        /// 
        #region 该方法主要是处理POST请求,返回处理的结果字符串
        public string GBTPost(string posturl, string postdata)
        {
            try
            {
                string responseString = "";//post返回的结果
                ServicePointManager.ServerCertificateValidationCallback
                            += RemoteCertificateValidate;
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(posturl);
                req.Method = "POST";
                //req.Headers["Cookie"] = "usersession=67d2da2c9f17e5e189fb1bf334fc6e36";
                byte[] postBytes = Encoding.UTF8.GetBytes(postdata);
                req.ContentType = "application/json; charset=utf-8";
                req.ContentLength = Encoding.UTF8.GetByteCount(postdata);//strJson为json字符串
                Stream stream = req.GetRequestStream();
                stream.Write(postBytes, 0, postBytes.Length);
                req.Timeout = 90000;
                stream.Close();
                var response = req.GetResponse();
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamRead = new StreamReader(streamResponse);
                responseString = streamRead.ReadToEnd();
                response.Close();
                streamRead.Close();
                return responseString;
            }
            catch
            {
                throw;
            }
        }
        #endregion
        
        #region 该方法主要是处理Get请求,返回处理的结果字符串
        public string GBTGet(string url)
        {
            try
            {
                //设置安全的类型
                ServicePointManager.ServerCertificateValidationCallback
                           += RemoteCertificateValidate;
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "GET";
                myRequest.ContentType = "application/json";
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                string content = reader.ReadToEnd();
                reader.Close();
                return content;
            }
            catch
            {
                throw;
            }
        }
        #endregion

        #region 从图片地址获取图片字节数据
        public byte[] GetImageFromResponse(string url, string cookie = null)
        {
            redo:
            try
            {
                WebRequest request = WebRequest.Create(url);
                if (!string.IsNullOrWhiteSpace(cookie))
                {
                    request.Headers[HttpRequestHeader.Cookie] = cookie;
                }

                WebResponse response = request.GetResponse();

                using (Stream stream = response.GetResponseStream())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        byte[] buffer = new byte[1024];
                        int current = 0;
                        do
                        {
                            ms.Write(buffer, 0, current);
                        } while ((current = stream.Read(buffer, 0, buffer.Length)) != 0);
                        return ms.ToArray();
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Message == "基础连接已经关闭: 发送时发生错误。")
                {
                    goto redo;
                }
                else
                {
                    throw;
                }
            }
        }
        #endregion
    }
}
